package com.manelrodriguez.applications.eurostoxx50.adapters;

import java.text.NumberFormat;
import java.util.List;

import android.content.Context;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.manelrodriguez.applications.eurostoxx50.R;
import com.manelrodriguez.applications.eurostoxx50.activity.Eurostoxx50Activity;
import com.manelrodriguez.applications.eurostoxx50.to.Empresa;
import com.manelrodriguez.applications.eurostoxx50.to.Movimiento;

public class CarteraListAdapter extends ArrayAdapter<Movimiento> {
	private int layoutResourceId;
	TextView tv_1;
	TextView tv_2;
	TextView tv_3;
	TextView tv_4;
	TextView tv_5;
	NumberFormat numberFormat;
	
	public CarteraListAdapter(Context context, int layoutResourceId, List<Movimiento> items){
		super(context, layoutResourceId, items);
        this.layoutResourceId = layoutResourceId;
        numberFormat = NumberFormat.getInstance();
		numberFormat.setMaximumFractionDigits(2);
	}
	
	@Override
    public View getView(int position, View convertView, ViewGroup parent) {
		RelativeLayout itemView;
		Movimiento mov = getItem(position);
		if(convertView==null)
		{
			itemView = new RelativeLayout(getContext());
			LayoutInflater vi = (LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			vi.inflate(layoutResourceId, itemView, true);
		}else{
			itemView = (RelativeLayout)convertView;
		}
		
		Empresa emp = Eurostoxx50Activity.hash_empresas.get(mov.getIdEmpresa());
		double precio = Double.valueOf(emp.getLastTradeAmount());
		double valorActual = precio * mov.getNumAcciones();
		double diferencia = valorActual-mov.getPrecioCompra();
		tv_1 = (TextView)itemView.findViewById(R.id.cartera_id_empresa_r);
		tv_2 = (TextView)itemView.findViewById(R.id.cartera_num_acciones_r);
		tv_3 = (TextView)itemView.findViewById(R.id.cartera_importe_r);
		tv_4 = (TextView)itemView.findViewById(R.id.cartera_valor_actual_r);
		tv_5 = (TextView)itemView.findViewById(R.id.cartera_diferencia_r);
		tv_1.setText(mov.getIdEmpresa());
		tv_2.setText(String.valueOf(numberFormat.format(mov.getNumAcciones())));
		tv_3.setText(String.valueOf(numberFormat.format(mov.getPrecioCompra())));
		tv_4.setText(String.valueOf(numberFormat.format(valorActual)));
		tv_5.setText(String.valueOf(numberFormat.format(diferencia)));
		if(diferencia>0){
			tv_5.setTextColor(Color.rgb(34, 177, 76));
		}else if(diferencia <0){
			tv_5.setTextColor(Color.RED);
		}
		return itemView;
	}
}
